import type { Type } from '@nestjs/common'
import { applyDecorators } from '@nestjs/common'
import {
  ApiExtraModels,
  ApiOkResponse,
  ApiProperty,
  getSchemaPath,
} from '@nestjs/swagger'

// 通用响应基类
class BaseResponseDto {
  @ApiProperty({ required: false })
  error?: string

  @ApiProperty()
  path: string

  @ApiProperty({ default: 200 })
  code: number

  @ApiProperty({ default: 'success' })
  message: string
}

// 针对对象类型的响应
export class ObjectResponseDto<T> extends BaseResponseDto {
  @ApiProperty({ type: () => Object }) // 这里保持通用，实际类型由装饰器指定
  data: T
}

// 针对数组类型的响应
export class ArrayResponseDto<T> extends BaseResponseDto {
  @ApiProperty({ type: () => [Object] }) // 这里保持通用，实际类型由装饰器指定
  data: T[]
}

export function ListApiResponse(dataType: Type) {
  return applyDecorators(
    ApiExtraModels(dataType, ArrayResponseDto),
    ApiOkResponse({
      schema: {
        allOf: [
          { $ref: getSchemaPath(ArrayResponseDto) },
          {
            properties: {
              data: {
                type: 'array',
                // 数组需要指定 items
                items: { $ref: getSchemaPath(dataType) },
              },
            },
          },
        ],
      },
    }),
  )
}

export function ObjectApiResponse(dataType: Type) {
  return applyDecorators(
    ApiExtraModels(dataType, ObjectResponseDto),
    ApiOkResponse({
      schema: {
        allOf: [
          { $ref: getSchemaPath(ObjectResponseDto) },
          {
            properties: {
              data: { $ref: getSchemaPath(dataType) },
            },
          },
        ],
      },
    }),
  )
}
